#include "updateserver.h"

#include <QTcpSocket>


void clearDir(const QString& path)
{
    QDir dir(path);
    QFileInfoList fileInfoList = dir.entryInfoList();
    QStringList fileList;
    QFile file;

    foreach(QFileInfo fileInfo, fileInfoList)
    {
        if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
            continue;

        if(!fileInfo.isDir())
        {
            file.remove(fileInfo.absoluteFilePath());
        } else {
            clearDir(fileInfo.absoluteFilePath());
        }
    }
    dir.rmdir(path);
}

UpdateServer::UpdateServer(QWidget *parent)
    : QWidget(parent)
{
    init();
}

UpdateServer::~UpdateServer()
{

}

void UpdateServer::listen(quint16 port)
{
    m_updateTcpServer->listen(QHostAddress::Any, port);
}


void UpdateServer::init()
{
    //更新之前先将更新文件夹里面的内容全部清空
    QString updatePath = g_installPath + "/" + UPDATEPATH;
    QDir dir;
    if (dir.exists(updatePath))
    {
        clearDir(updatePath);
    }

    m_updateTcpServer = new UpdateTcpServer(0, this);
    connect(m_updateTcpServer, SIGNAL(receUpdateState(int)), this, SIGNAL(receUpdateState(int)));
    connect(m_updateTcpServer, SIGNAL(clientDisconnect()),   this, SLOT(updateClientClose()));

    connButton = new QPushButton(this);
    connButton->setText("connect");
    connButton->setGeometry(20, 80, 100, 40);

    breakConnButton = new QPushButton(this);
    breakConnButton->setText("breakConn");
    breakConnButton->setGeometry(250, 80, 100, 40);

    stateLabel = new QLabel(this);
    stateLabel->setGeometry(20, 20, 200, 40);

}

void UpdateServer::updateClientClose()
{
//    qDebug() << "updateClientClose=============================>>";

}

//void UpdateServer::receUpdateState(const int state)
//{
//    //3个参数，1，程序路径 2，更新文件路径 3，保存副本路径

//    QString pgmPath = g_installPath;
//    QString updatePath = g_installPath + "/" + UPDATEPATH;
//    QString backupPath = g_installPath + "/" + BACKUPDATAPATH;
//}

